<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-left">
      <div class="tree-search">
        <el-input placeholder="输入分类搜索" v-model="filterText" clearable></el-input>
      </div>
      <el-tree :data="treeData" :props="treeProps" highlight-current ref="treeBox" :filter-node-method="filterNode"
        :default-expanded-keys="[-1]" :default-checked-keys="[-1]" @node-click="handleNodeClick" class="JNPF-common-el-tree" node-key="id">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <i :class="data.icon"></i>
          <span class="text">{{node.label}}</span>
        </span>
      </el-tree>
    </div>
    <div class="JNPF-common-layout-center">
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <div class="head-button">
            <el-button v-has="'btn_add'" type="primary"  @click="addOrUpdateHandle()">新增分类</el-button>
            <el-button v-has="'btn_upload'" plain @click="uploadForm">导入</el-button>
            <el-button v-has="'btn_download'" plain @click="exportData">导出</el-button>
            <el-button v-has="'btn_batchRemove'" type="danger" @click="handleBatchRemoveDel()">批量删除</el-button>
            <el-button plain @click="refresh()">刷新</el-button>
          </div>
          <div class="JNPF-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false" @click="getTreeView(true)" />
            </el-tooltip>
          </div>
        </div>
        <JNPF-table v-loading="listLoading" :data="list" :span-method="arraySpanMethod" has-c
          @selection-change="handleSelectionChange" :customColumn="true">
          <el-table-column prop="code" label="分类编码" align="left" />
          <el-table-column prop="name" label="分类名称" align="left" />
          <el-table-column prop="creatorUserName" label="创建人" align="left" show-overflow-tooltip />
          <el-table-column prop="creatorTime" label="创建时间" align="left" min-width="140" />
          <el-table-column prop="remark" label="备注" align="left" show-overflow-tooltip />
          <el-table-column label="操作" fixed="right" min-width="90">
            <template slot-scope="scope">
              <el-button v-has="'btn_edit'" type="text" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
              <el-button v-has="'btn_remove'" type="text" class="JNPF-table-delBtn" @click="handleDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </JNPF-table>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="批量删除进度"
      :visible.sync="askDialogVisible"
      width="400px"
    >
      <div class="askDialog">
        <div class="progressBox">
          <el-progress
            class="progress"
            :text-inside="true"
            :stroke-width="24"
            :percentage="parseInt(progressNum)"
          />
          <el-card v-if="isCard">
            <div>
              <div class="successes">成功数量：{{ successesNum }}</div>
              <div class="failures">失败数量：{{ failuresNum }}</div>
              <div class="information">
                <div v-for="(item, index) in information" :key="index">
                  <div class="informationText">{{ item }}</div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
        <div class="progressIcon" @click="isCard = !isCard">
          <i class="el-icon-yzzxiangqing" />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          @click="askDialogVisible = false"
        >关闭</el-button>
      </span>
    </el-dialog>
    <JNPF-Form v-if="formVisible" ref="JNPFForm" @refreshGoodsType="refreshGoodsType" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <ImportForm v-if="importFormVisible" ref="importForm" @refreshGoodsTypeImport="initData()" />
  </div>
</template>

<script>
  import { getGoodsTypeTree, getChildrenList, delGoodsType, batchRemoveGoodsType, exportGoodsType } from '@/api/asso/goods/category'
  import JNPFForm from './Form'
  import ExportBox from './ExportBox'
  import ImportForm from './ImportForm'
  import columnList from './columnList'

  export default {
    components: {
      JNPFForm,
      ExportBox,
      ImportForm
    },
    data() {
      return {
        expandObj: {},
        columnOptions: [],
        mergeList: [],
        exportList: [],
        columnList,

        treeProps: {
          children: 'children',
          label: 'name',
          value: 'id'
        },
        list: [],
        listLoading: true,
        multipleSelection: [],
        askDialogVisible: false,
        successesNum: 0, // 成功数
        failuresNum: 0, // 失败数
        information: [],
        progressNum: 0,
        isCard: false,
        total: 0,
        formVisible: false,
        exportBoxVisible: false,
        treeData: [{
          name: '商品分类',
          id:'-1',
          children: []
        }],
        treeActiveId: '',
        filterText: '',
        importFormVisible: false
      }
    },
    computed: {
      menuId() {
        return this.$route.meta.modelId || ''
      }
    },
    created() {
      this.getColumnList(),
      this.getTreeView();
    },
    watch: {
      filterText(val) {
        this.$refs.treeBox.filter(val);
      }
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      getColumnList() {
        // 没有开启权限
        this.columnOptions = this.transformColumnList(this.columnList)
      },
      transformColumnList(columnList) {
        let list = []
        for (let i = 0; i < columnList.length; i++) {
          const e = columnList[i];
          if (!e.prop.includes('-')) {
            list.push(e)
          } else {
            let prop = e.prop.split('-')[0]
            let label = e.label.split('-')[0]
            let vModel = e.prop.split('-')[1]
            let newItem = {
              align: "center",
              jnpfKey: "table",
              prop,
              label,
              children: []
            }
            e.vModel = vModel
            if (!this.expandObj.hasOwnProperty(`${prop}Expand`)) this.$set(this.expandObj, `${prop}Expand`, false)
            if (!list.some(o => o.prop === prop)) list.push(newItem)
            for (let i = 0; i < list.length; i++) {
              if (list[i].prop === prop) {
                list[i].children.push(e)
                break
              }
            }
          }
        }
        this.getMergeList(list)
        this.getExportList(list)
        return list
      },
      arraySpanMethod({
        column
      }) {
        for (let i = 0; i < this.mergeList.length; i++) {
          if (column.property == this.mergeList[i].prop) {
            return [this.mergeList[i].rowspan, this.mergeList[i].colspan]
          }
        }
      },
      getMergeList(list) {
        let newList = JSON.parse(JSON.stringify(list))
        newList.forEach(item => {
          if (item.children && item.children.length) {
            let child = {
              prop: item.prop + '-child-first'
            }
            item.children.unshift(child)
          }
        })
        newList.forEach(item => {
          if (item.children && item.children.length) {
            item.children.forEach((child, index) => {
              if (index == 0) {
                this.mergeList.push({
                  prop: child.prop,
                  rowspan: 1,
                  colspan: item.children.length
                })
              } else {
                this.mergeList.push({
                  prop: child.prop,
                  rowspan: 0,
                  colspan: 0
                })
              }
            })
          } else {
            this.mergeList.push({
              prop: item.prop,
              rowspan: 1,
              colspan: 1
            })
          }
        })
      },
      getExportList(list) {
        let exportList = []
        for (let i = 0; i < list.length; i++) {
          if (list[i].jnpfKey === 'table') {
            for (let j = 0; j < list[i].children.length; j++) {
              exportList.push(list[i].children[j])
            }
          } else {
            exportList.push(list[i])
          }
        }
        this.exportList = exportList
      },
      getTreeView(init) {
        if(init){
          this.treeActiveId = '-1'
        }
        getGoodsTypeTree().then(res => {
          if(res.code == 200){
            this.treeData[0].children = JSON.parse(JSON.stringify(res.data.list))
          }
          this.initData()
        })
      },
      getNodePath(node) {
        let fullPath = []
        const loop = (node) => {
          if (node.level) fullPath.unshift(node.data)
          if (node.parent) loop(node.parent)
        }
        loop(node)
        return fullPath
      },
      handleNodeClick(data, node) {
        this.treeActiveId = data.id
        this.initData()
      },
      initData() {
        let parentId = this.treeActiveId ? this.treeActiveId : '-1'
        getChildrenList(parentId).then((res) => {
          this.list = JSON.parse(JSON.stringify(res.data.list))
          this.total = res.data.pagination.total
          this.listLoading = false
        }).catch(()=>{
          this.listLoading = false
        })
      },
      handleDel(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          type: 'warning'
        }).then(() => {
          delGoodsType(id).then((res) => {
            if(res.code == 200){
              this.$message({
                type: 'success',
                message: res.msg,
                onClose: () => {
                  this.getTreeView()
                }
              })
            }else{
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }).catch(() => {});
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      batchDel(item, index) {
        return new Promise((resolve, reject) => {
          const num = 100 / this.multipleSelection.length
          delGoodsType(item.id).then((res) => {
            this.progressNum += num
            if (res.code === 200) {
              this.successesNum++
            } else {
              this.information.push(
                '商品分类' + item.name + ':' + res.msg
              )
              this.failuresNum++
            }
            resolve()
          })
        })
      },
      handleBatchRemoveDel() {
        if (!this.multipleSelection.length) {
          this.$message({
            type: 'error',
            message: '请选择一条数据',
            duration: 1500,
          })
          return
        }
        this.successesNum = 0
        this.failuresNum = 0
        this.progressNum = 0
        this.information = []
        this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
          type: 'warning'
        }).then(() => {
          this.askDialogVisible = true
          this.isCard = true
          const asyncFuns = []
          this.multipleSelection.forEach(async(item, index) => {
            asyncFuns.push(this.batchDel(item, index))
            if ((this.multipleSelection.length - 1) === index) {
              Promise.all(asyncFuns).then(() => {
                this.getTreeView()// 刷新页面
              })
            }
          })
        })
        .catch(() => {})
      },
      addOrUpdateHandle(id) {
        this.formVisible = true
        this.$nextTick(() => {
          this.$refs.JNPFForm.init(id)
        })
      },
      exportData() {
        // this.exportBoxVisible = true
        // this.$nextTick(() => {
        //   this.$refs.ExportBox.init(this.exportList)
        // })
        let parentId = this.treeActiveId ? this.treeActiveId : '-1'
        exportGoodsType(parentId).then((res) => {
          if (!res.data.url) return
          this.jnpf.downloadFile(res.data.url)
          // this.$refs.ExportBox.visible = false
          // this.exportBoxVisible = false
        })
      },
      download(data) {
        let query = {
          ...data,
          menuId: this.menuId
        }
        exportGoodsType(query).then((res) => {
          if (!res.data.url) return
          this.jnpf.downloadFile(res.data.url)
          this.$refs.ExportBox.visible = false
          this.exportBoxVisible = false
        })
      },
      refreshGoodsType(isrRefresh) {
        this.formVisible = false
        if (isrRefresh) this.getTreeView()
      },
      refresh(){
        var view = this.$route
        this.$store.dispatch('tagsView/delCachedView', view).then(() => {
          let { fullPath } = view
          this.$nextTick(() => {
            this.$router.replace({
              path: '/redirect' + fullPath
            })
          })
        })
      },
      uploadForm() {
        let parentId = this.treeActiveId ? this.treeActiveId : '-1'
        this.importFormVisible = true
        this.$nextTick(() => {
          this.$refs.importForm.init(parentId)
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .tree-search{
    margin: 10px 15px;
  }
  .head-button{
    .el-button--small{
      width: 80px;
    }
  }
  .table-tooltip {
  　　max-width: 500px;
  }
  .long_title{
  　　overflow: hidden;
  　　text-overflow: ellipsis;
  　　white-space: nowrap;
  }
</style>
